package com.chen.base.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 参数校验工具类
 * @author: ChenJinLong
 * @DATE: 2024/7/18
 **/
@Component
public class ValidateUtil implements ApplicationContextAware, DisposableBean {

    private static Validator validator = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ValidateUtil.validator = applicationContext.getBean(Validator.class);
    }

    /** 校验参数 */
    public static <T> String validate(T param){
        StringBuilder builder = new StringBuilder();
        Set<ConstraintViolation<T>> violations = validator.validate(param);
        for (ConstraintViolation<T> violation : violations) {
            String p = violation.getPropertyPath().toString();
            builder.append("参数").append(p)
                    .append(": ").append(violation.getMessage())
                    .append("; ");
        }
        return builder.toString();
    }

    /** 重要：实现DisposableBean接口，在Context关闭时清理静态变量 */
    @Override
    public void destroy() throws Exception {
        ValidateUtil.clearHolder();
    }

    /** 清除validator */
    public static void clearHolder(){
        validator = null;
    }
}
